import { Injectable } from '@nestjs/common';
// import { CreateUserDto } from './dto/create-user.dto';
import { Repository } from 'typeorm';
import { UpdateUserDto } from './dto/update-user.dto';
import { CreateUserDto } from './dto/create-user.dto';
import { User } from './entities/user.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Log } from 'src/logs/log.entity';

@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(User)
    private userRepository: Repository<User>,
    @InjectRepository(Log)
    private logsRepository: Repository<Log>,
  ) { }

  findLogsByGroup(id: number) {
    //   return this.logsRepository
    //     .query(`SELECT log.result AS result, COUNT( log.result ) AS count FROM log,
    // USER   WHERE
    //   USER.id = log.userId
    //   AND USER.id = 2
    // GROUP BY
    //   log.result`);
    return (
      this.logsRepository
        .createQueryBuilder('log')
        .select('log.result', 'result')
        .addSelect('COUNT("log.result")', 'count')
        .leftJoinAndSelect('log.user', 'user')
        .where('user.id = :id', { id })
        .groupBy('result')
        .orderBy('result', 'DESC')
        .addOrderBy('count', 'ASC')
        // .offset(2)
        // .limit(3)
        .getRawMany()
    );
  }

  async createUser(user: User): Promise<User> {
    const userTep = await this.userRepository.create(user);
    // 在这里添加用户创建逻辑
    return this.userRepository.save(userTep);
  }

  async findAllUsers(): Promise<User[]> {
    // 在这里添加获取所有用户逻辑
    return this.userRepository.find();
  }

  findAll() {
    return `This action returns all users`;
  }

  async findOne(id: number): Promise<User> {
    return await this.userRepository.findOne({ where: { id: id } });
  }

  async update(id: number, user: Partial<User>) {
    try {
      await this.userRepository.update(id, user);
      return {
        code: 200,
        message: 'Success',
      };
    } catch (e) {
      return {
        code: 400,
        message: e,
      };
    }
  }

  remove(id: number) {
    return this.userRepository.delete(id);
  }

  findProfile(id: number) {
    return this.userRepository.findOne({
      where: {
        id,
      },
      relations: {
        // 关联查询profile信息
        profile: true,
      },
    });
  }

  async findUserLogs(id: number) {
    const user = await this.findOne(id);
    return this.logsRepository.find({
      where: {
        user,
      },
      relations: {
        // 关联查询 log 信息
        user: true,
      },
    });
  }
}
